/*********************************************************
 *********************************************************
 ********************                  *******************
 *************                                ************
 *******                  _oo0oo_                  *******
 ***                     o8888888o                     ***
 *                       88" . "88                       *
 *                       (| -_- |)                       *
 *                       0\  =  /0                       *
 *                     ___/`---'\___                     *
 *                   .' \\|     |// '.                   *
 *                  / \\|||  :  |||// \                  *
 *                 / _||||| -:- |||||- \                 *
 *                |   | \\\  -  /// |   |                *
 *                | \_|  ''\---/''  |_/ |                *
 *                \  .-\__  '-'  ___/-. /                *
 *              ___'. .'  /--.--\  `. .'___              *
 *           ."" '<  `.___\_<|>_/___.' >' "".            *
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |          *
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /          *
 *      =====`-.____`.___ \_____/___.-`___.-'=====       *
 *                        `=---='                        *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      *
 *********__佛祖保佑__永无BUG__验收通过__钞票多多__*********
 *********************************************************/
package org.jbase.jbsc.commons.base.config.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.jbase.jbsc.commons.base.config.component.FileUploadComponent;
import org.jbase.jbsc.commons.base.utils.WebUtil;
import org.jbase.jbsc.commons.core.dto.Base64File;
import org.jbase.jbsc.commons.core.result.FileUploadResult;
import org.jbase.jbsc.commons.core.result.ResultBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Project: jbsc-commons <br/>
 * File: FileController.java <br/>
 * Class: org.jbase.jbsc.commons.base.config.web.FileController <br/>
 * Description: <描述类的功能>. <br/>
 * Copyright: Copyright (c) 2011 <br/>
 * Company: https://gitee.com/liuzp315 <br/>
 * Makedate: 2020/9/22 上午10:18 <br/>
 *
 * @author popo
 * @version 1.0
 * @since 1.0
 */
@Api(tags = "文件上传和下载的通用控制方法")
@RestController("org.jbase.jbsc.commons.base.config.web.FileController")
@RequestMapping("/file")
public class FileController {

    private static final Logger L = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileUploadComponent fileUploadComponent;

    @ApiOperation(value = "上传文件")
    @ApiImplicitParam(name = "file", value = "文件", required = true)
    @PostMapping("/upload")
    public ResultBean<FileUploadResult> uploadImage(@RequestParam(value = "file") MultipartFile file) {
        ResultBean rb = ResultBean.fireFail();
        if (file == null || file.isEmpty()) {
            return rb.setMsg("文件为空");
        }

        rb = fileUploadComponent.uploadFile(file);
        return rb;
    }

    @ApiOperation(value = "上传Base64到文件")
    @PostMapping("/uploadBase64")
    public ResultBean<FileUploadResult> uploadUploadFileBase64(@RequestBody Base64File base64File) {
        ResultBean rb = ResultBean.fireFail();
        rb = fileUploadComponent.uploadBase64(base64File);
        return rb;
    }

    @ApiOperation(value = "下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePath", value = "文件相对路径", required = true),
            @ApiImplicitParam(name = "outFileName", value = "下载的文件名", required = true)
    })
    @GetMapping("/download")
    public ResultBean download(@RequestParam(value = "filePath") String filePath, @RequestParam(value = "outFileName") String outFileName) {
        ResultBean rb = ResultBean.fireFail();

        File file = fileUploadComponent.findFileByPath(filePath);
        if (file == null)
            return rb.setMsg("文件不存在");

        HttpServletResponse response = WebUtil.getResponse();
        response.setContentType("application/x-download");
        try {
            outFileName = new String(outFileName.getBytes(), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + outFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int length = 1024;
        byte[] buffer = new byte[length];
        FileInputStream fis = null;
        BufferedInputStream bis = null;

        OutputStream os = null;
        try {
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer);
                buffer = new byte[length];
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            L.error("download error", e);
            return rb.setMsg("下载出错!");
        } finally {
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                L.error("close inputstream error", e);
            }
        }
        return rb.success();
    }


    /**
     * 获取base64图片数据
     *
     * @param filePath
     * @return
     */
    @ApiOperation(value = "获取base64图片数据")
    @ApiImplicitParam(name = "filePath", value = "文件相对路径", required = true)
    @GetMapping("/getImgBase64")
    public Object getImgBase64(@RequestParam("filePath") String filePath) {
        ResultBean rb = ResultBean.fireFail();
        String base64 = fileUploadComponent.findBase64ByPath(filePath);
        if (base64 == null)
            return rb.setMsg("文件不存在");
        return rb.success().setData(base64);
    }

    /**
     * 获取图片流
     *
     * @param filePath
     */
    @ApiOperation(value = "获取图片流")
    @ApiImplicitParam(name = "filePath", value = "文件相对路径", required = true)
    @GetMapping("/getImgStream")
    public ResultBean getImgStream(@RequestParam("filePath") String filePath) {
        ResultBean rb = ResultBean.fireFail();
        File file = fileUploadComponent.findFileByPath(filePath);
        if (file == null)
            return rb.setMsg("文件不存在");

        String fileName = file.getName();
        String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名
        HttpServletResponse response = WebUtil.getResponse();
        response.setContentType("image/" + suffixName);
        FileInputStream fis = null;
        try {
            OutputStream out = response.getOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            L.error("getImgStream error", e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    L.error("close getImgStream error", e);
                }
            }
        }
        return rb.success();
    }
}
